package com.itheima.putige.putige.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.putige.putige.common.BaseContext;
import com.itheima.putige.putige.common.CustomException;
import com.itheima.putige.putige.entity.*;
import com.itheima.putige.putige.mapper.OrderMapper;
import com.itheima.putige.putige.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * ClassName: OrderServiceImpl
 * Description:
 * date: 2022/3/1 19:27
 * 订单的提交
 *
 * @author zjf95
 * @since JDK 1.8
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;


    /**
     * Description:  提交订单
     *
     * @author: zjf95
     * @date: 2022/3/1 20:38
     * @param:
     * @return:
     */
    @Override
    public void submit(Orders orders) {

        log.info("订单信息为：{}",orders);
        //1. 获取用户id
        Long userId = BaseContext.getCurrentId();

        //2. 通过用户id来查询购物车的订单
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        //判断购物车实体类是否为空
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空");
        }

        //获取用户信息
        User user = userService.getById(userId);

        //获取地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        if (addressBook == null) {
            throw new CustomException("地址有误");
        }
        //id提取器，获取唯一id
        long orderId = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);

        //3. 将购物车以及订单的数据封装到订单明细实体类中
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            //判断是菜品还是套餐，并将销量更新
            Long dishId = item.getDishId();

            if (dishId != null) {
                //餐品
                Dish dish = dishService.getById(dishId);
                dish.setSaleNum(item.getNumber());
                dishService.updateById(dish);
            } else {
                //套餐
                Setmeal setmeal = setmealService.getById(item.getSetmealId());
                setmeal.setSaleNum(item.getNumber());
                setmealService.updateById(setmeal);
            }
            OrderDetail orderDetail = new OrderDetail();
            //设置订单明细的订单id
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(dishId);
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setImage(item.getImage());
            orderDetail.setName(item.getName());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            //计算出总金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());


        //将这些数据封装给orders表
        orders.setId(orderId);
        //设置订单时间和下单时间
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //订单号
        orders.setNumber(Long.toString(orderId));
        orders.setAmount(new BigDecimal(amount.get()));
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setPayMethod(1);
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //orders.setStatus(1);
        orders.setUserId(userId);
        orders.setUserName(user.getName());

        //保存订单信息
        this.save(orders);

        //将订单明细全部保存到数据库
        orderDetailService.saveBatch(orderDetails);

        //将购物车中的数据删除
        shoppingCartService.remove(queryWrapper);
    }
}
